﻿# encoding:utf-8

import json
from datetime import datetime, date

def jsonTest():
    sss = '''
    [{
        "name": "Tom",
        "gender": "male"
    }, {
        "name": "Jack",
        "gender": "male"   
    }]
    '''
    print('normal: '+sss)
    print('type: '+str(type(sss)))

    # json to object(list)
    data = json.loads(sss)
    print('type data: '+str(type(data)))
    print('data: '+str(data))

    # object(dict) to json
    data2 = json.dumps(data, indent=1)
    print('type data2: '+str(type(data2)))
    print('data2: '+str(data2))


def dict_to_json():
    dict = {}
    dict['name'] = 'many'
    dict['age'] = 10
    dict['sex'] = 'male'
    print(dict)  # 输出：{'name': 'many', 'age': 10, 'sex': 'male'}
    j = json.dumps(dict)
    print(j)  # 输出：{"name": "many", "age": 10, "sex": "male"}

class Student(object):
    def __init__(self, age, sex, mobile, date):
            self.age = age
            self.sex = sex
            self.mobile = mobile
            self.date = date

def obj_to_json():
    stu = Student(28, 'male', '13000000000', datetime.now())
    printJson(stu)

# 扩展 json 无法解析的类型
class ComplexEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime):
            # return obj.strftime('%Y-%m-%d %H:%M:%S')
            return str(obj)
        elif isinstance(obj, date):
            # return obj.strftime('%Y-%m-%d')
            return str(obj)
        else:
            try:
                return json.JSONEncoder.default(self, obj)
            except Exception as e:
                print('type not support: '+str(obj))
                # 默认的处理不了直接强转字符串
                return str(obj)

# json 对齐方式输出对象所有属性，方便查看
def printJson(obj):
    if hasattr(obj,'__dict__'):
        obj = obj.__dict__
    # ensure_ascii=False 中文不变成百分符
    # indent 缩进行增加的空格数
    j = json.dumps(obj, cls=ComplexEncoder, ensure_ascii=False, indent=4)
    print(j)

if __name__ == '__main__':
    obj_to_json()